<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>系统管理</title>
    <!--<base th:href="${#request.getContextPath()}+'/'">-->
    <base th:href="@{/}">
    <!--bootstrap.min.css-->
    <link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.min.css}">
    <script th:src="@{https://lib.baomitu.com/jquery/3.5.0/jquery.min.js}"></script>
    <script th:src="@{/bootstrap/js/bootstrap.min.js}"></script>
    <script th:src="@{/bootstrap/js/extendPagination.js}"></script>
    <script th:src="@{/bootstrap/js/layopen.js}"></script>
    <link rel="stylesheet" type="text/css" th:href="@{/bootstrap/css/my-layer-div.css}"/>
    <link rel="stylesheet" th:href="@{/bootstrap/font-awesome/css/font-awesome.min.css}">
    <link rel="stylesheet" th:href="@{/bootstrap/sys/css/bootstrap_table_render.css}">
    <style>
        .add-btn {
            display: block;
            float: right;
            padding: 5px 15px;
            background: #4cae4c;
            cursor: pointer;
            border-radius: 3px;
            color: #FFF;
        }

        .add-btn:hover {
            background-color: #449d44;
        }
    </style>
</head>
<body>
<ul class="nav nav-tabs" style="margin: 10px 20px 0;">
    <li data-type="User" class="active"><a href="javascript:void(0);">用户管理</a></li>
    <li data-type="Role"><a href="javascript:void(0);">角色管理</a></li>
    <li data-type="Perm"><a href="javascript:void(0);">权限管理</a></li>
    <span class="add-btn">添加</span>
</ul>
<div id="callBackPagination" class="piece">
    <!--border: 1px solid #ddd;-->
    <div id="mainContent"
         style="height: calc(100% - 130px);overflow-y: auto;"></div>
    <div id="callBackPager"></div>
</div>
</body>
<script th:src="@{/bootstrap/js/JSONUtil.js}"></script>
<script th:src="@{/layer/layer.js}"></script>
<script th:src="@{/bootstrap/js/AjaxUtil.js}"></script>
<script type="text/javascript">
    // 初始化参数 TODO 修改第二页无法编辑的问题==============================================
    var CACHE = [], TYPE = null, RELATION = [], RELATION_MAP = {};
    let totalCount = 252, showCount = 1, limit = 10;

    /**
     * 分页回调
     */
    window.onload = function (ev) {
        loadInitTable(showCount, limit, 'User');
    };


    $('.nav-tabs li').on('click', function () {
        totalCount = 252;
        showCount = 1;
        limit = 10;
        loadInitTable(showCount, limit, $(this).data('type'));
        $(this).addClass('active').siblings().removeClass('active');
    });


    /**
     * 建表(初始化数据)
     * @param data
     */
    function createTable(data) {
        let html = [];
        html.push(' <table class="table table-hover piece" style="margin-left: 0;">');
        // html.push(' <caption style="text-align: center;">您管理的日记</caption>');
        buildTableHtmlByType(html, data);
        html.push('</tbody></table>');
        var mainObj = $('#mainContent');
        mainObj.empty();
        mainObj.html(html.join(''));
    }

    /**
     * 构建表
     */
    function buildTableHtmlByType(html, data) {
        if (TYPE === 'User') {
            getRelation();
            html.push(' <thead><tr><th>用户名</th><th>号码</th><th>邮箱</th><th>角色</th><th>创建时间</th><th>操作</th></tr></thead><tbody>');
            if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    html.push('<tr><td>' + data[i].username + '</td>');
                    html.push('<td>' + data[i].mobile + '</td>');
                    html.push('<td>' + data[i].email + '</td>');
                    html.push('<td style="max-width: 520px;">' + createTag(data[i].userRole) + '</td>');
                    html.push('<td>' + (data[i].createTime ? data[i].createTime.replace(/T/, ' ') : '') + '</td>');
                    html.push('<td>' + createToolbar(data[i]) + '</td>');
                    html.push('</tr>');
                    data[i]['dataIndex'] = i;
                }
            }
        } else if (TYPE === 'Role') {
            getRelation();
            html.push(' <thead><tr><th>名称</th><th>编码</th><th>权限</th><th>创建时间</th><th>操作</th></tr></thead><tbody>');
            if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    html.push('<tr><td>' + data[i].name + '</td>');
                    html.push('<td>' + data[i].code + '</td>');
                    html.push('<td style="max-width: 520px;">' + createTag(data[i].rolePerm) + '</td>');
                    html.push('<td>' + (data[i].createTime ? data[i].createTime.replace(/T/, ' ') : '') + '</td>');
                    html.push('<td>' + createToolbar(data[i]) + '</td>');
                    html.push('</tr>');
                    data[i]['dataIndex'] = i;
                }
            }
        } else if (TYPE === 'Perm') {
            html.push(' <thead><tr><th>名称</th><th>编码</th><th>路径</th><th>创建时间</th><th>操作</th></tr></thead><tbody>');
            if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    html.push('<tr><td>' + data[i].name + '</td>');
                    html.push('<td>' + data[i].code + '</td>');
                    html.push('<td>' + data[i].url + '</td>');
                    html.push('<td>' + (data[i].createTime ? data[i].createTime.replace(/T/, ' ') : '') + '</td>');
                    html.push('<td>' + createToolbar(data[i]) + '</td>');
                    html.push('</tr>');
                    data[i]['dataIndex'] = i;
                }
            }
        }
    }


    /**
     * 工具栏
     */
    function createToolbar(data) {
        let key = getKeyName();
        return '<span onclick="editArticle(\'' + data[key] + '\')" class="tool_btn">编辑</span>' +
            '<span onclick="delArticle(\'' + data[key] + '\')" class="tool_btn">删除</span>';
    }

    /**
     * 编辑
     */
    function editArticle(key) {
        let row = getRowByKey(key);
        if (row !== null) {
            let url = 'sys/edit_' + TYPE.toLowerCase();
            let json = {title: "编辑" + getName(), area: 10, url: url};
            layopen(json, "init", {row: row, opt: 'edit', relation: RELATION});
        }
    }

    /**
     * 新增
     */
    $('.add-btn').on('click', function () {
        let url = 'sys/edit_' + TYPE.toLowerCase();
        let json = {title: "新增" + getName(), area: 10, url: url};
        layopen(json, "init", {opt: 'add', relation: RELATION});
    });

    function getName() {
        let name = '';
        if (TYPE === 'User') {
            name = '用户';
        } else if (TYPE === 'Role') {
            name = '角色';
        } else if (TYPE === 'Perm') {
            name = '权限';
        }
        return name;
    }

    /**
     * 成功回调
     */
    function editSuccessCallback(data) {
        let keyName = getKeyName();
        let row = getRowByKey(data[keyName]);
        updateRow(row, data);
        SuccessAlert('操作成功');
    }

    /**
     * 删除文章
     */
    function delArticle(key) {
        layer.confirm('您是是否需要删除此记录？', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            let row = getRowByKey(key), keyName = getKeyName();
            let url = 'sys/manage/delete' + TYPE, json = {};
            json[keyName] = key;
            ajaxSyncPost(url, json, function () {
                layer.load(1);
            }, function (result) {
                layer.closeAll("loading");
                if (result.code === 200) {
                    let dataIndex = row['dataIndex'];
                    removeCacheByKey(dataIndex);
                    $("#mainContent .table tbody tr").eq(dataIndex).remove();
                    SuccessAlert('删除成功');
                } else {
                    WarnAlert('请求数据失败, 请稍后重试');
                }
            }, function () {
                layer.closeAll("loading");
                ErrorAlert('后台请求出错, 请稍后重试');
            });
        }, function () {

        });
    }


    /**
     * 创建标签Dom
     */
    function createTag(tags) {
        let html = '';
        if (tags && tags.length > 0) {
            for (let i = 0; i < tags.length; i++) {
                let v = tags[i], key = '', fa = '';
                if (TYPE === 'User') {
                    key = 'roleKey';
                    fa = 'fa-fighter-jet'
                } else if (TYPE === 'Role') {
                    key = 'permKey';
                    fa = 'fa-usb';
                }
                let keyName = v[key];
                let role = RELATION_MAP[keyName];
                if (role) {
                    html += '<span style="font-size: .8rem;line-height: 15px;padding: 3px 5px;' +
                        'color: #888;border: 1px solid #888;border-radius: 2px;margin: 5px 5px 5px 0;' +
                        'display: block;float: left;">' +
                        '<i class="menu-item-icon fa ' + fa + ' fa-tags" style="margin-right: 5px;"></i>' + role.name + '</span>';
                }
            }
        }
        return html;
    }

    /**
     * 加载表格
     * @param curr
     * @param limit
     * @param totalCount
     * @param type
     */
    function loadTable(curr, limit, totalCount) {
        let url = 'sys/manage/pageGet' + TYPE;
        applyForPage(url, {pageIndex: curr, pageSize: limit}, function (result, count) {
            totalCount = count;
            CACHE = result;
            createTable(result);
        }, function (msg, code) {
            console.log('错误码: ' + code);
            WarnAlert(msg);
        });
    }

    /**
     * 初始化加载表格
     * @param curr
     * @param limit
     * @param type
     */
    function loadInitTable(curr, limit, type) {
        TYPE = type;
        let url = 'sys/manage/pageGet' + TYPE;
        applyForPage(url, {pageIndex: curr, pageSize: limit}, function (result, count) {
            CACHE = result;
            totalCount = count;
            createTable(CACHE);
            $('#callBackPager').extendPagination({
                totalCount: totalCount,
                showCount: showCount,
                limit: limit,
                callback: function (curr, limit, totalCount) {
                    loadTable(curr, limit, totalCount);
                    console.log('完事啦');
                }
            });
        }, function () {
            ErrorAlert('后台请求出错, 请稍后重试');
        });
    }

    /**
     * 获取关联数据
     */
    function getRelation() {
        let url = 'sys/manage/getAll' + getRelationKeyName();
        applySync(url, {}, function (result) {
            RELATION = result;
            if (RELATION.length > 0) {
                for (let i = 0; i < RELATION.length; i++) {
                    let v = RELATION[i];
                    if (TYPE === 'User') {
                        RELATION_MAP[v.roleKey] = v;
                    } else if (TYPE === 'Role') {
                        RELATION_MAP[v.permKey] = v;
                    }
                }
            }
        }, function () {
            ErrorAlert('后台请求出错, 请稍后重试');
        });
    }

    /**
     * 获取当行数据
     * @param key
     * @returns {*}
     */
    function getRowByKey(key) {
        for (let i = 0; i < CACHE.length; i++) {
            let v = CACHE[i];
            let keyName = getKeyName(TYPE);
            if ((v[keyName] + '') === (key + '')) {
                return v;
            }
        }
        return null;
    }

    /**
     * 更新行数据
     */
    function updateRow(row, data) {
        if (TYPE === 'User') {
            let userRole = getUserRole(data.userKey, data.roles);
            data['userRole'] = userRole;
        } else if (TYPE === 'Role') {
            let rolePerm = getRolePerm(data.roleKey, data.perms);
            data['rolePerm'] = rolePerm;
        }
        if (row) {
            let index = row['dataIndex'];
            updateRowCache(index, data);
            updateRowDom(index, data);
        } else {
            addRowCache(data);
            addRowDom(data);
        }
    }

    /**
     * 更新行Dom
     */
    function updateRowDom(dataIndex, data) {
        let $tr = $("#mainContent .table tbody tr").eq(dataIndex);
        if ($tr) {
            if (TYPE === 'User') {
                $tr.find("td").eq(0).text(data.username);
                $tr.find("td").eq(1).text(data.mobile);
                $tr.find("td").eq(2).text(data.email);
                let tags = createTag(data.userRole);
                $tr.find("td").eq(3).html(tags);
                // $tr.find("td").eq(4).text(data.createTime ? data.createTime.replace(/T/, ' ') : '');
                let opt = createToolbar(data);
                $tr.find("td").eq(5).html(opt);
            } else if (TYPE === 'Role') {
                $tr.find("td").eq(0).text(data.name);
                $tr.find("td").eq(1).text(data.code);
                let tags = createTag(data.rolePerm);
                $tr.find("td").eq(2).html(tags);
                // $tr.find("td").eq(3).text(data.createTime ? data.createTime.replace(/T/, ' ') : '');
                let opt = createToolbar(data);
                $tr.find("td").eq(4).html(opt);
            } else if (TYPE === 'Perm') {
                $tr.find("td").eq(0).text(data.name);
                $tr.find("td").eq(1).text(data.code);
                $tr.find("td").eq(2).text(data.url);
                // $tr.find("td").eq(3).text(data.createTime ? data.createTime.replace(/T/, ' ') : '');
                let opt = createToolbar(data);
                $tr.find("td").eq(4).html(opt);
            }
        }
    }

    /**
     *  添加Dom
     */
    function addRowDom(data) {
        let $table = $('#mainContent table tbody').eq(0),
            date = new Date(), html = '';
        if (TYPE === 'User') {
            html += '<tr><td>' + data.username + '</td>' +
                '<td>' + data.mobile + '</td>' +
                '<td>' + data.email + '</td>' +
                '<td style="max-width: 520px;">' + createTag(data.userRole) + '</td>' +
                '<td>' + JSONUtil.dateFormat("YYYY-mm-dd HH:MM:SS", date) + '</td>' +
                '<td>' + createToolbar(data) + '</td>' +
                '</tr>';
        } else if (TYPE === 'Role') {
            html += '<tr><td>' + data.name + '</td>' +
                '<td>' + data.code + '</td>' +
                '<td style="max-width: 520px;">' + createTag(data.rolePerm) + '</td>' +
                '<td>' + JSONUtil.dateFormat("YYYY-mm-dd HH:MM:SS", date) + '</td>' +
                '<td>' + createToolbar(data) + '</td>' +
                '</tr>';
        } else if (TYPE === 'Perm') {
            html += '<tr><td>' + data.name + '</td>' +
                '<td>' + data.code + '</td>' +
                '<td>' + data.url + '</td>' +
                '<td>' + JSONUtil.dateFormat("YYYY-mm-dd HH:MM:SS", date) + '</td>' +
                '<td>' + createToolbar(data) + '</td>' +
                '</tr>';
        }
        $table.append(html);
    }


    /**
     * 获取数据在缓存中的索引并替换他
     * @param dataIndex
     * @param data
     * @returns {null}
     */
    function updateRowCache(dataIndex, data) {
        data['dataIndex'] = dataIndex;
        removeCacheByKey(dataIndex);
        CACHE.push(data);
    }

    /**
     * 添加缓存
     */
    function addRowCache(data) {
        let trLen = $("#mainContent .table tbody tr").length;
        data['dataIndex'] = trLen;
        CACHE.push(data);
    }


    /**
     * 通过ID删除缓存数据
     * @param dataIndex
     */
    function removeCacheByKey(dataIndex) {
        for (let i = 0; i < CACHE.length; i++) {
            let v = CACHE[i];
            if (v.dataIndex === dataIndex) {
                CACHE.splice(i, 1);
                break;
            }
        }
        // 移动数据行索引
        for (let i = 0; i < CACHE.length; i++) {
            let v = CACHE[i];
            if (v.dataIndex > dataIndex) {
                let source = v.dataIndex;
                v['dataIndex'] = source - 1;
            }
        }
    }


    /**
     * 获取key 类型
     */
    function getKeyName() {
        let keyName = '';
        if (TYPE === 'User') {
            keyName = 'userKey';
        } else if (TYPE === 'Role') {
            keyName = 'roleKey';
        } else if (TYPE === 'Perm') {
            keyName = 'permKey';
        }
        return keyName;
    }


    /**
     * 获取key 类型
     */
    function getRelationKeyName() {
        let keyName = '';
        if (TYPE === 'User') {
            keyName = 'Role';
        } else if (TYPE === 'Role') {
            keyName = 'Perm';
        }
        return keyName;
    }


    /**
     * 合成List<UserRole>
     * @param userKey
     * @param roles
     * @returns {Array}
     */
    function getUserRole(userKey, roles) {
        let roleList = roles.split(","), result = [];
        for (let i = 0; i < roleList.length; i++) {
            let obj = {};
            let v = roleList[i];
            obj['userKey'] = userKey;
            obj['roleKey'] = v;
            result.push(obj);
        }
        return result;
    }

    /**
     * 合成List<RolePerm>
     * @param roleKey
     * @param perms
     * @returns {Array}
     */
    function getRolePerm(roleKey, perms) {
        let permList = perms.split(","), result = [];
        for (let i = 0; i < permList.length; i++) {
            let obj = {};
            let v = permList[i];
            obj['roleKey'] = roleKey;
            obj['permKey'] = v;
            result.push(obj);
        }
        return result;
    }

</script>
</html>